var express = require('express')

const usersRouter = require('./users/usersRouter')
const newsRouter = require('./newsRouter')
const doctorsMainRouter = require('./doctors/doctorsMainRouter')
const registraionRecordsRouter = require('./registraionRecordsRouter')
const statisticsRouter = require('./statisticsRouter')

const sqlQuery = require('../../module/sqlQuery')

var router = express.Router()

router.get('/', permisson, function (req, res, next) {
  res.render('admin/index.ejs', { user: req.session })
})

/**
 * 判断是否获取登录到后台的中间件
 */
function permisson(req, res, next) {
  // if (req.session.username === undefined) {
  //   // 未登录
  //   res.render('info/info.ejs', {
  //     title: '系统信息',
  //     content: '未登录',
  //     hrefUrl: '/rl/login',
  //     hrefTitle: '跳往登录页',
  //     info: '',
  //   })
  // } else {
  //   next()
  // }
  // 不判断，直接过
  next()
}

/**
 * 设置后台访问权限的中间件
 * 查询数据库中用户的权限信息
 */
async function authAdmin(req, res, next) {
  const sqlStr =
    'SELECT * FROM auth WHERE id in (SELECT authid FROM role_auth WHERE roleid = (SELECT roleid FROM `user` WHERE username=?))'
  const results = await sqlQuery(sqlStr, [req.session.username])

  console.log(results)

  let authFlag = results.some((item) => {
    // 以权限路径生成正则表达式，来测试访问路径
    // 限制必须以这个路径开头
    return new RegExp('^' + item.authurl).test(req.originalUrl)
  })

  if (authFlag) {
    next()
  } else {
    res.render('info/info.ejs', {
      title: '权限信息',
      content: '无权限',
      hrefUrl: '',
      hrefTitle: '',
      info: '',
    })
  }
}
// router.use(authAdmin)

// 后台用户管理模块
router.use('/users', permisson, usersRouter)
// 后台资讯管理
router.use('/news', permisson, newsRouter)
// 后台医生管理
router.use('/doctors', permisson, doctorsMainRouter)
// 后台患者管理
router.use('/records', permisson, registraionRecordsRouter)
// 系统统计
router.use('/statistics', permisson, statisticsRouter)

module.exports = router
